package C039;

import com.sun.source.tree.Tree;

import java.util.Set;
import java.util.TreeMap;

/**
 * ClassName: C03
 * Package: C039
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/31 15:30
 * @Version 1.0
 * @Since 1.0
 */
public class C03 {
    public static void main(String[] args) {
        System.out.println((int) 'a');
        System.out.println((int) 'A');
        System.out.println(countOfAtoms("K4(ON(SO3)2)2"));
        System.out.println(countOfAtoms("Mg(OH)2"));
        System.out.println(countOfAtoms("H50"));
    }

    static int where;

    public static String countOfAtoms(String formula) {
        where = 0;
        TreeMap<String, Integer> map = process(formula.toCharArray());
        StringBuilder res = new StringBuilder();
        Set<String> keys = map.keySet();
        if(keys.isEmpty()) {
           return "";
        }
        for (String key : keys) {
            Integer i = map.get(key);

            res.append(key);
            if(i > 1) {
                res.append(i);
            }
        }
        return res.toString();
    }

    private static TreeMap<String, Integer> process(char[] arr) {
        StringBuilder yuanzi = new StringBuilder();
        TreeMap<String, Integer> pre = null;
        TreeMap<String, Integer> res = new TreeMap<>();
        int cur = 0;
        while (where < arr.length && arr[where] != ')') {
            if (arr[where] >= 'A' && arr[where] <= 'Z' || arr[where] == '(') {
                merg(yuanzi ,res, pre, cur);
                yuanzi.setLength(0);
                cur = 0;
                pre = null;
                if(arr[where] == '(') {
                    where ++;
                    pre = process(arr);
                }else {
                    yuanzi.append(arr[where]);
                    where++;
                }
            } else if (arr[where] >= 'a' && arr[where] <= 'z') {
                yuanzi.append(arr[where]);
                where++;
            } else if (arr[where] >= '0' && arr[where] <= '9') {
                cur = cur * 10 + arr[where] - '0';
                where++;
            }
        }
        merg(yuanzi , res, pre, cur);
        where ++;
        return res;
    }


    public static void merg(StringBuilder yuanzi, TreeMap<String, Integer> res, TreeMap<String, Integer> pre, int cur) {
        cur = cur == 0 ? 1 : cur;
        // 处理之前的原子
        if (!yuanzi.isEmpty()) {
            res.put(yuanzi.toString(), res.getOrDefault(yuanzi.toString(), 0) + cur);
        }
        // 处理之前的(...) 中间的内容
        if(pre != null && !pre.isEmpty()) {

            Set<String> keys = pre.keySet();
            for (String key : keys) {
                res.put(key, res.getOrDefault(key, 0) + pre.get(key) * cur);
            }
        }
    }
}
